package com.nc.mem.tests;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.testng.Assert;
import org.testng.annotations.Test;

import com.nc.mem.serial.Serializer;
import com.nc.mem.serial.graph.asm.GraphSerializerFactory;
import com.nc.mem.tests.GraphTest.Vertex;

@Test()
public class GraphTestSimple {

	static class Edge {
		Graph owner;

		public void test(final Graph graph) {
			Assert.assertSame(owner, graph);
		}

	}

	static class Graph {

		List<Edge> edges = new ArrayList<Edge>(4);

		public void add(final Edge edge) {
			edges.add(edge);
			edge.owner = this;
		}

		public void test() {
			Assert.assertTrue(edges.size() > 0);
			for (final Edge edge : edges) {
				edge.test(this);
			}
		}

		@Override
		public String toString() {
			return "Graph [edges=" + edges + "]";
		}

	}

	public static Graph build() {
		return build(2);
	}

	public static Graph build(final int edges) {
		final Graph graph = new Graph();

		final int verts = edges + 1;

		Vertex src = null;

		for (int i = 0; i < verts; i++) {
			final Vertex dest = new Vertex();
			dest.id = i;
			if (src != null) {
				final Edge edge = new Edge();

				graph.add(edge);
			}
			src = dest;
		}

		return graph;
	}

	@Test
	public void testReadWriteGraph() {

		final ByteBuffer buffer = ByteBuffer.allocateDirect(4096);

		final Serializer serializer = GraphSerializerFactory.serializer(Graph.class);

		final Graph original = build();
		original.test();

		serializer.write(buffer, original);

		final Graph recovered = (Graph) serializer.read((ByteBuffer) buffer.position(0));

		recovered.test();

		Assert.assertNotSame(recovered, original);

		// Assert.assertEquals(original, recovered);
	}
}
